package com.epoint.netty.chat.handler;

import com.epoint.netty.chat.message.ChatRequestMessage;
import com.epoint.netty.chat.message.ChatResponseMessage;
import com.epoint.netty.chat.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ChatRequestHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage message) throws Exception {
        String from = message.getFrom();
        String to = message.getTo();
        String content = message.getContent();

        Channel toChannel = SessionFactory.getSession().getChannel(to);

        if(toChannel == null){
            Channel fromChannel = SessionFactory.getSession().getChannel(from);
            ChatResponseMessage chatResponseMessage = new ChatResponseMessage("system", "对方不在线!");
            fromChannel.writeAndFlush(chatResponseMessage);
        }
        else{
            ChatResponseMessage chatResponseMessage = new ChatResponseMessage(from, content);
            toChannel.writeAndFlush(chatResponseMessage);
        }
    }
}
